package com.letfox.ad.util;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

import org.apache.commons.codec.binary.Base64;

public class GzipUtil {
    
	/**
	 * 压缩
	 * @param str
	 * @param encoding
	 * @return
	 * @throws UnsupportedEncodingException
	 * @throws IOException
	 */
    public static String compress(String str, String encoding) throws UnsupportedEncodingException, IOException {
        if (str == null || str.length() == 0) {
            return null;
        }
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        GZIPOutputStream gzip;
        gzip = new GZIPOutputStream(out);
        gzip.write(str.getBytes(encoding));
        gzip.close();
        return new String(Base64.encodeBase64(out.toByteArray()));
    }
    
    /**
     * 解压
     * @param byString
     * @return
     * @throws IOException
     */
    public static String uncompress(String byString) throws IOException{
        if (byString == null || byString.length() == 0) {
            return null;
        }
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        GZIPInputStream in = new GZIPInputStream(new ByteArrayInputStream(Base64.decodeBase64(byString))); 
        byte[] buffer = new byte[256];
        int n;
        while ((n = in.read(buffer)) >= 0) {
           out.write(buffer, 0, n);
        }
        return new String(out.toByteArray());
    }
}
